import {
    createAGroupFolder,
    getPlayerData,
    isGroupExist,
    isPlayerExist,
    storagePlayerData,
    deletePlayerData,
    ensureGroupAndPlayerExist,
    getConfig,
    formatCurrency,
    checkPermission
} from "../function/function.js";
import lodash from 'lodash'
import fs from 'fs';

// 读取文案配置文件
const copywriting = JSON.parse(fs.readFileSync('plugins/Slave-Market/resources/data/workCopywriting.json', 'utf-8'))

export class Sm extends plugin {
    constructor() {
        super({
            name: '[Sm]购买奴隶',
            dsc: '购买奴隶',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/]购买(群友|奴隶)(\d+)?/, fnc: 'purchaseSlaves' }
            ]
        })
    }

    async purchaseSlaves(e) {
        if (!e.isGroup) return e.reply(['该游戏只能在群内使用']);
        const ID = [e.user_id, e.group_id];

        // 禁止购买机器人
        if (e.atme) return e.reply(['不可以购买我捏~']);

        // 初始化玩家数据
        ensureGroupAndPlayerExist(ID[1], ID[0], e.sender.card || e.sender.nickname);

        // 获取目标奴隶ID
        let slave = e.at;
        if (!slave) slave = e.msg.replace(/#|\/|购买|群友|奴隶|\s/g, '');
        slave = parseInt(slave);

        // 如果目标在群中，也初始化他的数据
        const memberInfo = (await Bot.pickGroup(ID[1]).getMemberMap()).get(Number(slave));
        if (memberInfo) {
            ensureGroupAndPlayerExist(ID[1], slave, memberInfo.card || memberInfo.nickname);
        }

        // 禁止购买自己
        if (slave === ID[0]) return e.reply(['不可以购买自己捏~']);

        try {
            // 获取群成员列表
            const memberInfoList = Object.fromEntries([...await Bot.pickGroup(ID[1]).getMemberMap()]);

            // 检查目标是否在群内
            if (!memberInfoList[slave]) return e.reply([`本群不存在[${slave}]`]);

            slave = parseInt(slave);

            // 如果目标没有游戏数据，则初始化
            if (!isPlayerExist(ID[1], slave)) {
                storagePlayerData(ID[1], slave, {
                    currency: 0,      // 初始金币
                    slave: [],        // 拥有的奴隶列表
                    value: 100,       // 初始身价
                    lastWorkingTime: 0, // 上次工作时间
                    master: ''        // 主人ID
                });
            }

            // 获取玩家和目标的数据
            const userData = await getPlayerData(ID[1], ID[0]);
            const slaveData = await getPlayerData(ID[1], slave);

            const { currency } = userData;
            const { currency: slavecurrency, value: slavevalue, master: slaveMaster } = slaveData;

            // 检查是否已经是主人
            if (slaveMaster === ID[0]) return e.reply([
                segment.at(ID[0]),
                '你已经是他的主人了'
            ]);

            // 检查是否有足够的金币
            if (currency < slavevalue) return e.reply([
                segment.at(ID[0]),
                `你买不起！需要${slavevalue}金币`
            ]);

            // 检查购买冷却时间
            const config = getConfig();
            const currentSecond = Math.floor(Date.now() / 1000);
            const purchaseCooldown = config.purchase.cooldown;

            if (!checkPermission(e) && currentSecond - (userData.lastPurchaseTime || 0) < purchaseCooldown) {
                const remainingTime = purchaseCooldown - (currentSecond - (userData.lastPurchaseTime || 0));
                return e.reply([`购买冷却中，剩余时间：${Math.floor(remainingTime / 3600)}小时${Math.floor((remainingTime % 3600) / 60)}分钟`]);
            }

            // 禁止购买自己的主人
            if (slave === userData.master) {
                return e.reply(lodash.sample(copywriting.buyMaster));
            }

            // 处理购买自由玩家的情况
            if (slaveMaster === '') {
                // 更新买家数据
                userData['currency'] = formatCurrency(userData['currency'] - slavevalue);
                userData['slave'].push(slave);
                userData['lastPurchaseTime'] = currentSecond;
                storagePlayerData(ID[1], ID[0], userData);

                // 更新被购买者数据
                slaveData['currency'] = formatCurrency(slaveData['currency'] + slavevalue);
                slaveData['value'] = formatCurrency(slaveData['value'] + 20);
                slaveData['master'] = ID[0];
                storagePlayerData(ID[1], slave, slaveData);

                return e.reply([`成功购买了${memberInfoList[slave]['nickname']}！花费了${slavevalue}金币，还剩${currency - slavevalue}金币\n${memberInfoList[slave]['nickname']}获得了${slavevalue}金币，现在拥有${slavecurrency + slavevalue}金币，身价上涨${slavevalue}->${slavevalue + 20}`]);
            } else {
                // 处理购买他人奴隶的情况
                const formerOwnerData = await getPlayerData(ID[1], slaveMaster);

                // 更新买家数据
                userData['currency'] = formatCurrency(userData['currency'] - slavevalue);
                userData['slave'].push(slave);
                userData['lastPurchaseTime'] = currentSecond;
                storagePlayerData(ID[1], ID[0], userData);

                // 更新被购买者数据
                slaveData['currency'] = formatCurrency(slaveData['currency'] + slavevalue);
                slaveData['value'] = formatCurrency(slaveData['value'] + 20);
                slaveData['master'] = ID[0];
                storagePlayerData(ID[1], slave, slaveData);

                // 更新原主人数据
                formerOwnerData['currency'] = formatCurrency(formerOwnerData['currency'] + slavevalue);
                formerOwnerData['slave'] = formerOwnerData['slave'].filter(a => a !== slave);
                storagePlayerData(ID[1], slaveMaster, formerOwnerData);

                // 如果原主人已不在群内，删除其数据
                if (!memberInfoList[slaveMaster]) {
                    deletePlayerData(ID[1], slaveMaster);
                    return e.reply([`${slaveMaster}已不在本群，已删除该用户存档\r已将其奴隶解放`]);
                }

                return e.reply([`成功从${memberInfoList[slaveMaster]['nickname']}那里购买了${memberInfoList[slave]['nickname']}！花费了${slavevalue}金币，还剩${currency - slavevalue}金币\n${memberInfoList[slaveMaster]['nickname']}获得了${slavevalue}金币，现在拥有${formerOwnerData['currency']}金币\n${memberInfoList[slave]['nickname']}额外获得了${slavevalue / 10}金币，现在拥有${slavecurrency + slavevalue / 10}金币，身价上涨${slavevalue}->${slavevalue + 20}`]);
            }
        } catch (error) {
            logger.error('处理购买请求时出错:', error);
            return e.reply(['处理请求时出错，请稍后再试。']);
        }
    }
}
